package popup

import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.PopupWindow
import android.widget.TextView
import app.AppContext
import com.hontech.pizzav2.R
import event.OtaProgressChanged
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class McuOtaWindow {

    companion object {
        var isShow = false
            private set
        val Instance: McuOtaWindow by lazy { McuOtaWindow() }
    }

    private val mView = LayoutInflater.from(AppContext).inflate(R.layout.popup_mcu_ota, null)
    private val mTextView = mView.findViewById<TextView>(R.id.id_mcu_ota_text_view)
    private val mWindow = PopupWindow(mView, 500, 500, true)

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onProgressChangedEvent(env: OtaProgressChanged) {
        when (env.status) {
            OtaProgressChanged.STATUS_OK -> {
                mTextView.text = String.format("Progress\r\n%d%%",
                    env.current * 100 / env.total )
            }
            OtaProgressChanged.STATUS_ERROR -> {
                mTextView.text = "Error"
            }
            OtaProgressChanged.STATUS_SUCCESS -> {
                mTextView.text = "Success"
            }
            OtaProgressChanged.STATUS_COMPLETE -> {
                dismiss()
            }
        }
    }

    private fun dismiss() {
        if (!isShow) {
            return
        }
        EventBus.getDefault().unregister(this)
        isShow = false
        mWindow.dismiss()
    }

    fun show(view: View) {
        if (isShow) {
            return
        }
        mTextView.text = ""
        mWindow.showAtLocation(view, Gravity.CENTER, 0, 0)
        isShow = true
        EventBus.getDefault().register(this)
    }

}
